﻿using System.Collections;
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;

public class SlotShow : MonoBehaviour
{

    private GameObject slotGrid;        //滚动区域
    public GameObject Item;
    public int SlotLength = 4;
    private List<Image> slotItems;
    private float itemHeight;
    private List<Color> testColor;      //测试用,应该从数据里读
    public float rollSpeed = 0.1f;        //滚动速度
    private Vector3 rollStartPosition;

    void Start()
    {
        Init();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Z))
            StartCoroutine(StartSlot());
    }

    void Init()
    {
        testColor = new List<Color>()
        {
            Color.white,
            Color.red,
            Color.green,
            Color.white
        };
        slotItems = new List<Image>();
        slotGrid = transform.GetChild(0).gameObject;
        itemHeight = slotGrid.GetComponent<GridLayoutGroup>().cellSize.y;
        for (int i = 0; i < 4; i++)
        {
            GameObject tempItem = (GameObject) Instantiate(Item);
            tempItem.transform.parent = slotGrid.transform;
            slotItems.Add(tempItem.GetComponent<Image>());
            tempItem.GetComponent<Image>().color = testColor[i];
        }
        rollStartPosition = new Vector3(0, (SlotLength - 1)*itemHeight, 0);
        slotGrid.transform.localPosition = rollStartPosition;
    }

    IEnumerator StartSlot()
    {
        int count = 0;
        Vector3 slotRollLength = new Vector3(0, 1100, 0);
        Vector3 deltaLength;
        //Vector3 startPosition = new Vector3(0, (SlotLength - 1) * itemHeight, 0);
        bool isFinished = false;
        while (!isFinished)
        {
            deltaLength = Vector3.Lerp(slotRollLength, Vector3.zero, 0.98f);
            slotRollLength -= deltaLength;
            slotGrid.transform.localPosition -= deltaLength;
            if (slotGrid.transform.localPosition.y < 1f)
            {
                slotGrid.transform.localPosition = rollStartPosition;
                count++;
                if (slotRollLength.y < rollStartPosition.y)
                    slotRollLength.y = 200;
            }
            if (slotRollLength.y < 100)
                isFinished = true;
            yield return 0;
        }
    }
}
